<template>
  <div class="track-play">
    <div class="back" @click="goBack">
      <span>← 返回</span>
    </div>
    
    <div id="track-map" ref="mapContainer"></div>
    
    <!-- 播放器控制栏 -->
    <div class="video-controls">
      <div class="control-bar">
        <!-- 播放控制按钮 -->
        <div class="control-buttons">
          <button @click="rePlay" class="control-btn" title="重新播放">
            🔄
          </button>
          <button @click="fastRewind" class="control-btn" title="快退10秒">
            ⏪
          </button>
          <button @click="playTrack" :disabled="!trackData.length" class="control-btn play-btn" title="播放/暂停">
            <span v-if="!isPlaying">▶</span>
            <span v-else>⏸</span>
          </button>
          <button @click="fastForward" class="control-btn" title="快进10秒">
            ⏩
          </button>
          <div class="speed-control">
            <select v-model="playbackSpeed" @change="changeSpeed" class="speed-select">
              <option value="0.5">0.5x</option>
              <option value="1">1x</option>
              <option value="2">2x</option>
              <option value="4">4x</option>
            </select>
          </div>
        </div>
        
        <!-- 时间显示 -->
        <div class="time-display">
          <span>{{ currentTime }} / {{ totalTime }}</span>
        </div>
      </div>
      
      <!-- 进度条 -->
      <div class="progress-container">
        <input 
          type="range" 
          :min="0" 
          :max="totalSeconds" 
          v-model="currentSeconds" 
          @input="handleSliderChange"
          :disabled="!trackData.length"
          class="progress-slider"
        />
      </div>
    </div>
    
    <!-- 位置信息 -->
    <div class="position-info">
      <span>缩放: {{ zoom }} | 坐标: {{ lat.toFixed(4) }}, {{ lng.toFixed(4) }}</span>
    </div>
    
    <!-- 轨迹列表切换按钮 -->
    <div class="track-list-toggle" @click="toggleTrackList">
      <span v-if="!showTrackList">📋</span>
      <span v-else>✕</span>
    </div>
    
    <!-- 轨迹列表 -->
    <transition name="slide">
      <div v-if="showTrackList" class="track-list-panel">
        <h3>轨迹列表</h3>
        <div class="track-options">
          <button @click="generateRandomTrack" class="option-btn">
            🎲 生成随机轨迹
          </button>
          <button @click="generateCircleTrack" class="option-btn">
            🔵 生成圆形轨迹
          </button>
          <button @click="clearTrack" class="option-btn">
            🗑️ 清除轨迹
          </button>
        </div>
        <div class="track-info">
          <p>轨迹点数: {{ trackData.length }}</p>
          <p>总时长: {{ totalTime }}</p>
          <p>当前点: {{ currentPointIndex + 1 }}</p>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'

// 修复 Leaflet 默认图标路径问题
delete (L.Icon.Default.prototype as any)._getIconUrl
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
  iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
})

interface TrackPoint {
  lat: number
  lng: number
  timestamp: number
  speed: number
}

const mapContainer = ref<HTMLElement>()
const map = ref<L.Map>()
const tileLayer = ref<L.TileLayer>()
const trackData = ref<TrackPoint[]>([])
const currentPointIndex = ref(0)
const isPlaying = ref(false)
const playbackSpeed = ref(1)
const playbackInterval = ref<number>()
const showTrackList = ref(false)

// 播放器相关状态
const currentSeconds = ref(0)
const totalSeconds = ref(0)
const zoom = ref(13)
const lat = ref(34.3416)
const lng = ref(108.9398)

// 轨迹相关元素
const trackLine = ref<L.Polyline>()
const currentMarker = ref<L.Marker>()
const trackMarkers = ref<(L.Marker | L.CircleMarker)[]>([])

// 平滑移动相关状态
const isSmoothMoving = ref(false)
const smoothMoveInterval = ref<number>()
const currentInterpolation = ref(0) // 0-1之间的插值
const lastUpdateTime = ref(0)

// 计算属性
const currentTime = computed(() => {
  return formatTime(currentSeconds.value)
})

const totalTime = computed(() => {
  return formatTime(totalSeconds.value)
})

// 格式化时间
const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 返回上一页
const goBack = () => {
  console.log('返回上一页')
}

// 初始化地图
const initMap = () => {
  if (!mapContainer.value) return

  map.value = L.map(mapContainer.value).setView([34.3416, 108.9398], 13)

  tileLayer.value = L.tileLayer(
    "https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    { attribution: '© 高德地图' }
  ).addTo(map.value)

  map.value.on('mousemove', (e) => {
    lat.value = e.latlng.lat
    lng.value = e.latlng.lng
  })

  map.value.on('zoomend', () => {
    zoom.value = map.value?.getZoom() || 13
  })

  generateDefaultTrack()
}

// 生成默认轨迹
const generateDefaultTrack = () => {
  const baseLat = 25.0330
  const baseLng = 102.7000
  const points: TrackPoint[] = []
  
  for (let i = 0; i < 20; i++) {
    const angle = (i / 20) * 2 * Math.PI
    const radius = 0.01
    const lat = baseLat + radius * Math.cos(angle)
    const lng = baseLng + radius * Math.sin(angle)
    
    points.push({
      lat,
      lng,
      timestamp: Date.now() + i * 1000,
      speed: 30 + Math.random() * 20
    })
  }
  
  trackData.value = points
  totalSeconds.value = 60
  drawTrack()
}

// 生成随机轨迹
const generateRandomTrack = () => {
  const baseLat = 25.0330
  const baseLng = 102.7000
  const points: TrackPoint[] = []
  
  let currentLat = baseLat
  let currentLng = baseLng
  
  for (let i = 0; i < 15; i++) {
    const angle = Math.random() * 2 * Math.PI
    const distance = 0.005 + Math.random() * 0.01
    
    currentLat += distance * Math.cos(angle)
    currentLng += distance * Math.sin(angle)
    
    points.push({
      lat: currentLat,
      lng: currentLng,
      timestamp: Date.now() + i * 1000,
      speed: 20 + Math.random() * 40
    })
  }
  
  trackData.value = points
  totalSeconds.value = 45
  currentPointIndex.value = 0
  currentSeconds.value = 0
  currentInterpolation.value = 0
  drawTrack()
}

// 生成圆形轨迹
const generateCircleTrack = () => {
  const baseLat = 25.0330
  const baseLng = 102.7000
  const points: TrackPoint[] = []
  
  for (let i = 0; i < 30; i++) {
    const angle = (i / 30) * 2 * Math.PI
    const radius = 0.015 + Math.sin(angle * 3) * 0.005
    const lat = baseLat + radius * Math.cos(angle)
    const lng = baseLng + radius * Math.sin(angle)
    
    points.push({
      lat,
      lng,
      timestamp: Date.now() + i * 1000,
      speed: 25 + Math.random() * 30
    })
  }
  
  trackData.value = points
  totalSeconds.value = 90
  currentPointIndex.value = 0
  currentSeconds.value = 0
  currentInterpolation.value = 0
  drawTrack()
}

// 绘制轨迹
const drawTrack = () => {
  if (!map.value || trackData.value.length === 0) return

  if (trackLine.value) {
    map.value.removeLayer(trackLine.value)
  }
  trackMarkers.value.forEach(marker => {
    if (map.value && marker) {
      map.value.removeLayer(marker as unknown as L.Layer)
    }
  })
  trackMarkers.value = []

  const latlngs = trackData.value.map(point => [point.lat, point.lng])
  trackLine.value = L.polyline(latlngs as [number, number][], {
    color: '#007bff',
    weight: 4,
    opacity: 0.7
  }).addTo(map.value)

  trackData.value.forEach((point, index) => {
    if (map.value) {
      const marker = L.circleMarker([point.lat, point.lng], {
        radius: 6,
        fillColor: index === 0 ? '#28a745' : '#ffc107',
        color: '#fff',
        weight: 2,
        opacity: 1,
        fillOpacity: 0.8
      }).addTo(map.value)

      marker.bindPopup(`点 ${index + 1}<br>速度: ${point.speed.toFixed(1)} km/h`)
      trackMarkers.value.push(marker)
    }
  })

  if (trackLine.value) {
    map.value.fitBounds(trackLine.value.getBounds(), { padding: [20, 20] })
  }
}

// 播放轨迹
const playTrack = () => {
  if (trackData.value.length === 0) return

  // 如果动画已经结束，重新开始播放
  if (currentSeconds.value >= totalSeconds.value) {
    currentSeconds.value = 0
    currentPointIndex.value = 0
    currentInterpolation.value = 0
  }

  isPlaying.value = !isPlaying.value
  
  if (isPlaying.value) {
    startSmoothPlayback()
  } else {
    pauseTrack()
  }
}

// 开始平滑播放
const startSmoothPlayback = () => {
  if (isSmoothMoving.value) return
  
  isSmoothMoving.value = true
  lastUpdateTime.value = Date.now()
  
  const animate = () => {
    if (!isSmoothMoving.value) return
    
    const now = Date.now()
    const deltaTime = (now - lastUpdateTime.value) / 1000 // 转换为秒
    lastUpdateTime.value = now
    
    if (currentSeconds.value < totalSeconds.value) {
      // 根据播放速度计算时间增量，使用更精确的时间控制
      const timeIncrement = deltaTime * Number(playbackSpeed.value)
      currentSeconds.value = Math.min(currentSeconds.value + timeIncrement, totalSeconds.value)
      
      updateSmoothPosition()
      
      // 使用固定的帧率来确保动画平滑
      setTimeout(() => {
        requestAnimationFrame(animate)
      }, 16) // 约60fps
    } else {
      pauseTrack()
    }
  }
  
  // 开始动画循环
  requestAnimationFrame(animate)
}

// 暂停轨迹
const pauseTrack = () => {
  isPlaying.value = false
  isSmoothMoving.value = false
  
  if (playbackInterval.value) {
    clearInterval(playbackInterval.value)
    playbackInterval.value = undefined
  }
  
  if (smoothMoveInterval.value) {
    clearInterval(smoothMoveInterval.value)
    smoothMoveInterval.value = undefined
  }
}

// 重新播放
const rePlay = () => {
  pauseTrack()
  currentSeconds.value = 0
  currentPointIndex.value = 0
  currentInterpolation.value = 0
  updateCurrentPosition()
  
  // 立即开始播放
  isPlaying.value = true
  startSmoothPlayback()
}

// 快退10秒
const fastRewind = () => {
  const newTime = Math.max(0, currentSeconds.value - 10)
  currentSeconds.value = newTime
  currentInterpolation.value = 0
  updateCurrentPosition()
}

// 快进10秒
const fastForward = () => {
  const newTime = Math.min(totalSeconds.value, currentSeconds.value + 10)
  currentSeconds.value = newTime
  currentInterpolation.value = 0
  updateCurrentPosition()
}

// 切换播放速度
const changeSpeed = () => {
  if (isPlaying.value) {
    pauseTrack()
    playTrack()
  }
}

// 进度条变化
const handleSliderChange = () => {
  currentInterpolation.value = 0
  updateCurrentPosition()
}

// 更新平滑位置
const updateSmoothPosition = () => {
  if (!map.value || trackData.value.length === 0) return

  // 基于时间的更精确插值计算
  const totalProgress = currentSeconds.value / totalSeconds.value
  const totalPoints = trackData.value.length - 1
  
  // 计算当前应该在哪两个点之间，使用更精确的浮点数计算
  const currentPointFloat = totalProgress * totalPoints
  
  // 确定当前段落的起始点索引
  const currentSegmentIndex = Math.floor(currentPointFloat)
  currentPointIndex.value = Math.min(currentSegmentIndex, trackData.value.length - 2)
  
  // 计算在当前段落中的插值 (0-1)，使用更精确的计算
  const segmentProgress = currentPointFloat - currentSegmentIndex
  currentInterpolation.value = Math.max(0, Math.min(1, segmentProgress))
  
  // 修复：确保能到达最后一个点
  let currentIndex = Math.min(currentPointIndex.value, trackData.value.length - 2)
  let startPoint = trackData.value[currentIndex]
  let endPoint = trackData.value[currentIndex + 1]
  
  // 如果已经到达最后一个点，直接使用最后一个点
  if (currentSeconds.value >= totalSeconds.value) {
    currentIndex = trackData.value.length - 1
    startPoint = trackData.value[currentIndex]
    endPoint = startPoint
    currentInterpolation.value = 1
  }
  
  if (!startPoint || !endPoint) return

  // 使用线性插值，确保速度均匀
  const easedT = currentInterpolation.value
  
  // 线性插值计算当前位置
  const currentLat = startPoint.lat + (endPoint.lat - startPoint.lat) * easedT
  const currentLng = startPoint.lng + (endPoint.lng - startPoint.lng) * easedT
  
  // 速度插值
  const currentSpeed = startPoint.speed + (endPoint.speed - startPoint.speed) * easedT
  
  updateMarkerPosition(currentLat, currentLng, currentSpeed, currentIndex + 1)
}

// 更新当前位置
const updateCurrentPosition = () => {
  if (!map.value || trackData.value.length === 0) return

  const progress = currentSeconds.value / totalSeconds.value
  const pointIndex = Math.floor(progress * (trackData.value.length - 1))
  
  // 修复：确保能到达最后一个点
  if (currentSeconds.value >= totalSeconds.value) {
    currentPointIndex.value = trackData.value.length - 1
  } else {
    currentPointIndex.value = Math.min(pointIndex, trackData.value.length - 1)
  }

  const currentPoint = trackData.value[currentPointIndex.value]
  
  updateMarkerPosition(currentPoint.lat, currentPoint.lng, currentPoint.speed, currentPointIndex.value + 1)
}

// 更新标记位置
const updateMarkerPosition = (lat: number, lng: number, speed: number, pointNumber: number) => {
  if (!map.value) return
  
  // 移除之前的当前位置标记
  if (currentMarker.value) {
    map.value.removeLayer(currentMarker.value)
  }

  // 创建带有移动效果的图标
  const customIcon = L.divIcon({
    className: 'current-position-marker',
    html: `<div style="
      width: 20px; 
      height: 20px; 
      background-color: #dc3545; 
      border: 3px solid white; 
      border-radius: 50%; 
      box-shadow: 0 2px 8px rgba(0,0,0,0.3);
      animation: pulse 1s infinite;
      transform: scale(${isSmoothMoving.value ? 1.1 : 1});
    "></div>`,
    iconSize: [20, 20],
    iconAnchor: [10, 10]
  })

  currentMarker.value = L.marker([lat, lng], { icon: customIcon })
    .addTo(map.value)
    .bindPopup(`当前位置: 点 ${pointNumber}<br>速度: ${speed.toFixed(1)} km/h`)

  // 优化地图移动动画
  if (isSmoothMoving.value) {
    // 播放时使用更平滑的移动，减少动画时间并优化缓动
    map.value.panTo([lat, lng], { 
      animate: true, 
      duration: 0.3,
      easeLinearity: 0.25
    })
  } else {
    // 非播放时使用标准移动
    map.value.panTo([lat, lng], { animate: true, duration: 0.5 })
  }
}

// 清除轨迹
const clearTrack = () => {
  pauseTrack()
  trackData.value = []
  currentPointIndex.value = 0
  currentSeconds.value = 0
  totalSeconds.value = 0
  currentInterpolation.value = 0
  
  if (trackLine.value && map.value) {
    map.value.removeLayer(trackLine.value)
  }
  
  trackMarkers.value.forEach(marker => {
    if (map.value && marker) {
      map.value.removeLayer(marker as unknown as L.Layer)
    }
  })
  trackMarkers.value = []
  
  if (currentMarker.value && map.value) {
    map.value.removeLayer(currentMarker.value)
  }
}

// 切换轨迹列表显示
const toggleTrackList = () => {
  showTrackList.value = !showTrackList.value
}

// 组件挂载时初始化地图
onMounted(() => {
  initMap()
})

// 组件卸载时清理
onUnmounted(() => {
  pauseTrack()
  if (map.value) {
    map.value.remove()
  }
})
</script>

<style scoped>
.track-play {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: #000;
}

#track-map {
  width: 100%;
  height: 100%;
  z-index: 1;
}

.back {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 2000;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 15px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.back:hover {
  background: rgba(0, 0, 0, 0.9);
}

/* 播放器控制栏 */
.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: 20px;
  z-index: 1000;
}

.control-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.control-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.control-btn {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.control-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.play-btn {
  width: 50px;
  height: 50px;
  background: rgba(255, 255, 255, 0.3);
  font-size: 20px;
}

.speed-control {
  margin-left: 10px;
}

.speed-select {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  padding: 5px 8px;
  font-size: 12px;
}

.speed-select option {
  background: #333;
  color: white;
}

.time-display {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

/* 进度条 */
.progress-container {
  width: 100%;
}

.progress-slider {
  width: 100%;
  height: 6px;
  border-radius: 3px;
  background: rgba(255, 255, 255, 0.2);
  outline: none;
  -webkit-appearance: none;
}

.progress-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #007bff;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.progress-slider::-moz-range-thumb {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #007bff;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

/* 位置信息 */
.position-info {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 12px;
  z-index: 1000;
}

/* 轨迹列表切换按钮 */
.track-list-toggle {
  position: absolute;
  top: 20px;
  right: 200px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  z-index: 1000;
  transition: all 0.3s ease;
}

.track-list-toggle:hover {
  background: rgba(0, 0, 0, 0.9);
}

/* 轨迹列表面板 */
.track-list-panel {
  position: absolute;
  top: 70px;
  right: 20px;
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
  min-width: 250px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  z-index: 1000;
}

.track-list-panel h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
}

.track-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
}

.option-btn {
  padding: 8px 12px;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  color: #495057;
  transition: all 0.3s ease;
}

.option-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
  transform: translateY(-1px);
}

.track-info {
  font-size: 12px;
  color: #666;
}

.track-info p {
  margin: 5px 0;
}

/* 动画 */
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  opacity: 0;
  transform: translateX(100%);
}

/* 确保 Leaflet 样式正确加载 */
:deep(.leaflet-container) {
  font-family: inherit;
}

:deep(.current-position-marker) {
  background: transparent;
  border: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .control-bar {
    flex-direction: column;
    gap: 10px;
  }
  
  .control-buttons {
    justify-content: center;
  }
  
  .time-display {
    text-align: center;
  }
  
  .track-list-panel {
    right: 10px;
    left: 10px;
    min-width: auto;
  }
  
  .track-list-toggle {
    right: 10px;
  }
  
  .position-info {
    right: 10px;
    top: 60px;
  }
}
</style> 